<template>
	<view class="cu-modal bottom-modal" v-if="isShow" :class="{'show':2}" >
	  <view class="cu-dialog">
			<view class="goods-data" style="height:220rpx;">
				<view class="thumb">
					<image :src="goodsInfo.images[0]" mode=""></image>
				</view>
				<view class="item" >

          <view class="title flex-box" style="align-items: flex-start;justify-content: flex-start;">
            <text class="box-1 two-omit" style="text-align:left;">{{goodsInfo.name}}</text>
            <view>
              <u-icon @click="hide" name="close" color="#000" size="22"></u-icon>
            </view>
          </view>
          <view v-if="!skuerror">
            <view class="price flex-box" style="margin-top:10rpx;justify-content: space-between;">
              <view class="box-1" style="text-align: left;">
                <text class="min">￥</text>
                <text class="max">{{tatalPrice?tatalPrice:goodsInfo.price0}}</text>

              </view>
              <view style="font-size:24rpx;color:#999;" v-if="sigle_price">折合单价:{{sigle_price}}</view>
              <!-- <text class="min">.00</text> -->
            </view>
            <view class="inventory" v-if="freight_money > 0">
              <text  style="font-size: 12px;display: block">含运费:￥{{ freight_money }}</text>
            </view>
            <view class="inventory">

              <text>库存：{{stock}}</text>
            </view>
          </view>


				  <view v-else style="text-align: left;
    padding: 16px 0px;
    color: #aaa;">
            {{skuerrorMsg}}
          </view>


				</view>
			</view>
			<view class="adres flex-box" @click="onSkip('address')">
				<view class="box-1" >
					配送至：{{address.province+' - '+address.city+' - '+address.district}}
				</view>
				<u-icon name="arrow-down" color="#999" size="16"></u-icon>
			</view>
			<view class="attr-size">
				<!-- <view class="attr-list" v-for="(item,index) in AttrSizeList" :key="index">
					<view class="title">
						<text>{{item.attr}}</text>
					</view>
					<view class="size-list">
						<div class="list" v-for="(value,idx) in item.SizeList" 
						:class="{'action':AttrSizeList[index].index === idx}"
						@click.stop="onAttrSize(item,value,index,idx)" :key="idx">
							<text>{{value.size}}</text>
						</div>
					</view>
				</view> -->
				<view class="attr-list">
					<view class="title">
						<text>有效期</text>
					</view>
					<view class="size-list">
						<div class="list" v-for="(value,idx) in GoodsAttr.life" 
						:class="{'action':lifeCheck == idx||lifeCheckLife==value}"
						@click.stop="onAttrLife(value,idx)" :key="idx">
							<text>{{value}}</text>
						</div>
					</view>
				</view>
				<view class="attr-list">
					<view class="title">
						<text>规格</text>
					</view>
					<view class="size-list">
						<div class="list" v-for="(value,idx) in GoodsAttr.sku" 
						v-if="GoodsAttr.life[lifeCheck]==value.life||skuCheck==idx"
						:class="skuCheck==idx?'action':(GoodsAttr.life[lifeCheck]!=value.life?'check1':'check2')"
						@click.stop="onAttrSku(GoodsAttr.life[lifeCheck],value,idx)" :key="idx">
							<text>{{value.spec}}</text>
						</div>
					</view>
				</view>
				<view class="attr-number" @click.stop="onStop">
					<view class="tit">数量</view>
					<view class="number">
						<!-- <text class="iconfont icon-jian"></text>
						<input type="tel" value="1" maxlength="8">
						<text class="iconfont icon-jia"></text> -->
						<u-number-box v-model="numValue" integer @change="valChange"></u-number-box>
					</view>
				</view>
			</view>

			<view class="attr-btn" v-if="!skuerror">
				<view class="add-cart" @click="lowPrice">一键最低价</view>
				 <!-- v-if="BuyType === 1" -->
				<!-- @click="onConfirm(BuyType)" -->
				<!-- <view class="add-buy" v-if="BuyType === 1" @click="onConfirm(BuyType)">一键最低价</view> -->
				<view class="confirm" @click="sendCart">确定</view>
				 <!--v-if="BuyType === 2 || BuyType === 3" @click="onConfirm(BuyType)" -->
			</view>

      <view class="attr-btn" v-else>

        <!-- v-if="BuyType === 1" -->
        <!-- @click="onConfirm(BuyType)" -->
        <!-- <view class="add-buy" v-if="BuyType === 1" @click="onConfirm(BuyType)">一键最低价</view> -->
        <view class="confirm" style="width: 100%;background: #eee">补货中</view>
        <!--v-if="BuyType === 2 || BuyType === 3" @click="onConfirm(BuyType)" -->
      </view>


    </view>
		<!-- <u-action-sheet :actions="address" cancelText="新增地址" :title="title" :show="showaddress"></u-action-sheet> -->
		<u-popup :closeOnClickOverlay="true" :show="showaddress" :round="10" mode="bottom" @close="showaddress=false" @open="showaddress=true">
			<view class="asContent address-input">
				<view class="b-title">配送至</view>
				<view  v-if="dataList.length" style="min-height:250rpx;overflow: auto;">
					<view class="address-mess flex-box"
					v-for="(item,index) in dataList" :key="index">
						<u-icon name="edit-pen" size="35" @tap="edit(item)"></u-icon>
						<view class="box-1"  @tap="exchangeAddress(item)" >
							<view class="flex-box">
								<text class="name">{{item.uname}}</text> <text class="tel">{{item.mobile}}</text>
							</view>
							<view class="one_ell">
								<text class="address-in" v-if="item.is_default">默认</text>
								{{item.province+item.city+item.district+item.address}}
							</view>
						</view>
						<!-- <uni-icons type="trash-filled"></uni-icons> -->
						<!-- <u-icon name="trash-fill" size="20" @tap="deleteAddress(item.id,index)"></u-icon> -->
				
					</view>
				</view>
				<u-empty v-else mode="data" marginTop="100" text="暂无数据"></u-empty>
				<!-- 添加地址 -->
				<view class="add-address">
					<view class="btn" @click="onAddressEdit(2)">
						<text>新建收货地址</text>
					</view>
				</view>
				
			</view>
		</u-popup>
	</view>
</template>

<script>
	import qqmapsdk from "@/utils/qqmap-wx-jssdk.min";
  import {watch} from "@vue/composition-api";

  export default {
		props:{
			hasLogin:{
				type:Boolean,
				default(){
					return false
				}
			},
			type:{
				type: String,
				default(){
					return ''
				}
			},
      skuerror:{
				type: Boolean,
				default(){
					return false
				}
			},
      skuerrorMsg:{
				type: String,
				default(){
					return ''
				}
			},
			isShow:{
				type:Boolean,
				default(){
					return false
				}
			},
			tab:{
				type: Number,
				default(){
					return 0
				}
			},
			goodsInfo:{
				type: Object,
				default(){
					return {}
				}
			},
			GoodsAttr: {
				type: Object,
				default(){
					return []
				}
			}
		},
		data() {
			return {
				sigle_price:null,
				dataList:[],
				showaddress: false,
				list: [
					{
						name:'选项一',
						subname:"选项一描述",
						color:'#ffaa7f',
						fontSize:'20'
					},
					{
						name: '选项二禁用',
						disabled:true
					},
					{
						name: '开启load加载', //开启后文字不显示
						loading:true
					}
				],
				stock:0,
				skuId:null,
				numValue:1,
				skuCheck:null,
				lifeCheck:0,
				AttrIndex: 0,
				SizeIndex: 0,
				AttrSizeList:[
					{
						index: 0,
						attr: '颜色',
						SizeList: [
							{
								index: 0,
								size: '白色'
							},{
								index: 1,
								size: '黑色'
							},{
								index: 2,
								size: '粉丝'
							},{
								index: 3,
								size: '灰色'
							},
						],
					},{
						index: 0,
						attr: '尺码',
						SizeList: [
							{
								index: 0,
								size: 'M尺码'
							},{
								index: 1,
								size: 'L尺码'
							},{
								index: 2,
								size: 'XL尺码'
							},{
								index: 3,
								size: 'XXL尺码'
							},
						],
					}
				],
				// 购买类型
				BuyType: 0,
				lifeCheckLife:'',

				address:{
					province : '北京市',
					city : '北京市',
					district : '东城区',
					district_id : 110101
				},
				goodId:null,
				code:null,
        freight_money:0.00
			};
		},
		onLoad(){
			//默认地址
			this.lifeCheck = 0;
			this.code = uni.getStorageSync("code")
			this.goodId = uni.getStorageSync("goodsId")

      // console.log("onLoad")
		},
    onReady() {
    /*  watch(this.isShow,()=>{
        console.log(this.isShow)
      })*/
      // console.log("onReady")
    },
    watch:{
      isShow(){
        if (this.isShow){
          this.initData();
        }
      },
      dataList(){
        this.skuCheck = null
        this.lifeCheck = 0
      }
    },
    computed:{
			tatalPrice(){
				if(this.skuCheck!=null){
					return (this.GoodsAttr.sku[this.skuCheck]?.price0*this.numValue).toFixed(2)
				}
			},
			onePrice(){
				if(this.skuCheck!=null){
					return this.GoodsAttr.sku[this.skuCheck]?.price0
				}
			}
		},
    methods:{
			/**
			 * 编辑地址点击
			 */
			onAddressEdit(type){
				uni.navigateTo({
					url: '/pages/sub/AddressEdit/AddressEdit?type=' + type,
				})
			},
			edit(para){
				uni.navigateTo({
					url:'/pages/sub/AddressEdit/AddressEdit?typeb='+2+'&item='+encodeURIComponent(JSON.stringify(para))
				})
			},
			// 修改
			exchangeAddress(item){
				this.address = item
				this.showaddress = false
				this.$emit('changeAid',item.district_id);
				this.$emit('changeAddress',item);
        let data = {...item};
        data.is_default = 1;
        this.$u.api.addressEdit(data)
            .then(res=>{

            }).catch(err=>{
              console.log(err);
              uni.showToast({
                icon: 'none',
                title: "网络异常，请稍后再试"
              })
            });
			},
			initData(){
				this.$u.api.addressList()
				.then(res=>{
					if(res.status){
            let flag = false;
            res.msg.forEach((item)=>{
              if (item.is_default === 1){
                this.address = {...item};
                this.$emit('changeAddress',this.address);
                flag = true;
                // this.skuCheck = null
              }
            });
            if (res.msg.length > 0 && !flag){
              this.address = {...res.msg[0]};
              this.$emit('changeAddress',this.address);
            }
						this.dataList = res.msg
            // console.log(	this)
						// return
					}else{
            this.getgLocation();
          }

				})
				.catch(err=>{
					console.log(err);
					uni.showToast({
						icon: 'none',
						title: "网络异常，请稍后"
					})
				})
			},
      getgLocation() {
        // if(!this.hasLogin) return
        const QQMapWX = new qqmapsdk({
          key: 'DJFBZ-7W6KD-EII4D-PIKJI-WPF5Z-MEBAO'
        });
        let _this = this
        uni.getLocation({
          type: 'wgs84', // 返回国测局经纬度坐标系统的结果
          success(res) {
            // console.log('成功获取到位置信息：', res);
            const latitude = res.latitude; // 纬度
            const longitude = res.longitude; // 经度
            _this.latitude = latitude
            _this.longitude = longitude
            uni.setStorageSync('mylatitude', latitude);
            uni.setStorageSync('mylongitude', longitude);
            // 解析地址
            QQMapWX.reverseGeocoder({
              location: {
                latitude: _this.latitude,
                longitude: _this.longitude
              },
              success: function(res) {
                // console.log("解析地址成功");
                // console.log(res);
                // 省
                let province = res.result.ad_info.province;
                // 市
                let city = res.result.ad_info.city;
                _this.province = city
                _this.address.province = province;
                // this.province = province;
                _this.address.city = city;
                _this.address.district = res.result.ad_info.district;
                _this.address.district_id = res.result.ad_info.adcode;
                _this.$emit('changeAddress',_this.address);
            /*    province : '北京市',
                    city : '北京市',
                    district : '东城区',
                    district_id : 110101*/

              },
              fail: function(res) {
                uni.showToast({
                  title: '定位失败',
                  duration: 2000,
                  icon: "none"
                })
                console.log(res);
              },
              complete: function(res) {

               /* console.log("定位信息");
                console.log(res);*/
              }
            })
            // TODO: 根据需要进行后续操作
            // callback()
          },
          fail(err) {
            console.error('获取位置失败：', err);
            // TODO: 处理获取位置失败情况
          }
        });
      },
			/**
			 * 跳转点击
			 * @param {String} type 跳转类型
			 */
			onSkip(type){
				if(!this.hasLogin){
					uni.navigateTo({
					  url: '/pages/login/login?id='+this.id+'&scene='+this.code,
					})
					return false
				}
        this.initData();
				this.showaddress = true
				return 
			  switch (type){
			    case 'address':
			      uni.navigateTo({
			        url: '/pages/sub/AddressList/AddressList',
			      })
			      break;
			  }
			},
			// 一件最低
			lowPrice(){
				let arr = null
				let that = this
				this.skuCheck = null
				this.lifeCheck = null
				this.GoodsAttr.sku.forEach(function(item,index,arr){
					console.log(item,index,)
					if(item.min_price===1){
						arr = item
						// console.log(item,index,'index222222')
						that.skuCheck = index
						that.lifeCheckLife = item.life
            const keys = Object.keys(that.GoodsAttr.life);
            const foundKey = keys.find(key => that.GoodsAttr.life[key] === item.life);
            // let leftKey  =that.GoodsAttr.left.indexOf(item.life)
            // console.log(that.GoodsAttr.life.indexOf(item.life),"leftkey")
            that.lifeCheck = foundKey;
						that.stock = item.stock
						// let ids = arr.indexOf(3)
						that.skuId = item.id
						that.sigle_price = item.sigle_price
            return;
					}
				})
			},
			sendCart(){
				if(!this.skuId || this.skuCheck === null){
					uni.showToast({
						icon: 'none',
						title: '请选择规格'
					})
					return false
				}
				// if(this.type=='1101'){
					//保税商品
					let ids = this.skuId+":"+this.numValue
					this.$emit('closeShow',false)
					this.$f.jump('/pages/ConfirmOrder/ConfirmOrderConverge?par='+ids+'&type='+1+`&district_id=${this.address.district_id}&buy_area=${this.address.province+' - '+this.address.city+' - '+this.address.district}`);
				/*}else{
					this.$u.api.cartOperate({sku_id:this.skuId,type:'add',num:this.numValue}).then(res => {
						this.$emit('closeShow',false)
						if (res.status) {
							uni.showToast({
								icon: 'none',
								title: '添加购物车成功'
							})
						}else{
							uni.showToast({
								icon: 'none',
								title: res.msg
							})
						}
					})
					.catch(err => {
						console.log(err);
					})
				}*/
				
			},
			valChange(e) {
				console.log('当前值为: ' + e.value)
				this.numValue = e.value
			},
			onAttrLife(item,index){
				this.lifeCheckLife = ''
				this.lifeCheck = index
				this.skuCheck = null
				this.skuId = null
				this.sigle_price = null
			},
			onAttrSku(life,item,index){
				if(life!=item.life){
					return false
				}
				this.skuCheck = index
				this.skuId = item.id
				this.stock = item.stock
				this.sigle_price = item.sigle_price
        this.freight_money = item.freight_money
			},
			/**
			 * 显示 
			 * @param {Number} type 1 点击选择 2 加入购物 3 立即购买
			 */
			show(type){
				this.BuyType = type;
				// this.isShow = true;
			},
			hide(){
				// this.isShow = false;
				this.$emit('closeShow',false)
			},
			onStop(){
				
			},
			/**
			 * 属性选择点击
			 */
			onAttrSize(item,value,index,idx){
				this.AttrSizeList[index].index = idx;
				this.AttrIndex = item.index;
				this.SizeIndex = value.index;
			},
			/**
			 * 确认点击
			 */
			onConfirm(type){
				uni.navigateTo({
					url: '/pages/ConfirmOrder/ConfirmOrder'
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	@import 'GoodsAttr.scss';
	.asContent{
		padding:30rpx;
		.b-title{
			margin-bottom:30rpx;
			font-size:36rpx;
			text-align: center;
		}
	}
	.page{
		position: absolute;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		background-color: #FFFFFF;
		font-size:28rpx;
	}
	.one_ell{
		text-align: left;
		.address-in{
			
			color:red;
			
			margin-right:10rpx;
			// padding:1px 20rpx;
		}
	}
	/* 地址列表 */
	.address-list{
		width: 100%;
		background-color: #FFFFFF;
		padding-bottom: 120rpx;
		.list{
			padding: 0 4%;
			height: 160rpx;
			border-bottom: 2rpx solid #f6f6f6;
			.name-phone{
				display: flex;
				align-items: center;
				width: 100%;
				height: 80rpx;
				.name{
					display: flex;
					align-items: center;
					width: 30%;
					height: 100%;
					text{
						width: 100%;
						font-size: 26rpx;
						font-weight: bold;
						color: #222222;
					}
				}
				.phone{
					display: flex;
					align-items: center;
					width: 70%;
					height: 100%;
					text{
						font-size: 28rpx;
						font-weight: bold;
						color: #222222;
					}
					.tag{
						padding: 4rpx 8rpx;
						font-size: 24rpx;
						color: #FFFFFF;
						background-color: $base;
						border-radius: 4rpx;
						margin-left: 20rpx;
					}
					.blue{
						background-color: #0099FF;
					}
				}
			}
			.address-edit{
				display: flex;
				align-items: center;
				justify-content: space-between;
				width: 100%;
				height: 60rpx;
				.address{
					display: flex;
					align-items: center;
					width: 90%;
					height: 100%;
					text{
						font-size: 26rpx;
						color: #959595;
					}
				}
				.edit{
					display: flex;
					align-items: center;
					justify-content: flex-end;
					width: 10%;
					height: 100%;
					text{
						font-size: 38rpx;
						color: #555555;
					}
				}
			}
		}
	}
	
	/* 添加地址 */
	.add-address{
		// position: fixed;
		// left: 0;
		// bottom: 20rpx;
		// display: flex;
		// align-items: center;
		// justify-content: center;
		// width: 100%;
		// height: 100rpx;
		.btn{
			display: flex;
			align-items: center;
			justify-content: center;
			width: 80%;
			height: 70rpx;
			background:#d0abf4;
			border-radius: 70rpx;
			box-shadow: 0 10rpx 10rpx #d0abf4;
			margin:30rpx auto;
			// box-shadow: 0 10rpx 10rpx $base;
			text{
				font-size: 28rpx;
				color: #FFFFFF;
			}
		}
	}
	.app-address-list{
		
		position: relative;
		button{
			position:fixed;
			bottom:20rpx;
			left:50%;
			z-index:1;
			margin-left:-345rpx;
		}
	}
		
	.address-mess{
		background: #fff;
		// font-size: 26rpx;
		color: #999;
		padding:20rpx;
		margin-bottom:20rpx;
		border-bottom:1rpx solid #eee;
		.box-1{
			margin-left:10rpx;
		}
		.name{
			
			color: #333;
			margin-bottom:10rpx;
			margin-right:10rpx;
		}
	
	}
</style>
